package com.sdkj.dspservice.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sdkj.dspservice.common.base.service.impl.TreeServiceImpl;
import com.sdkj.dspservice.common.config.Global;
import com.sdkj.dspservice.common.utils.StringUtils;
import com.sdkj.dspservice.modules.sys.dao.MenuDao;
import com.sdkj.dspservice.modules.sys.entity.Menu;
import com.sdkj.dspservice.modules.sys.service.MenuService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 菜单表service实现类
 *
 * @author tm
 * @version 2020/11/23 18:09
 */
@Service
@Transactional(readOnly = true)
public class MenuServiceImpl extends TreeServiceImpl<MenuDao, Menu> implements MenuService {

    @Transactional(readOnly = false)
    @Override
    public boolean saveOrUpdate(Menu menu) {
        if(StringUtils.isBlank(menu.getPermission()) && StringUtils.isNotBlank(menu.getHref())){
            menu.setPermission(Arrays.stream(menu.getHref().split("/")).filter(x->StringUtils.isNotBlank(x)).collect(Collectors.joining(":")));
        }
        // 如果是根菜单
        if(StringUtils.isBlank(menu.getParentId())){
            // 获取根菜单href中的数字，取最大值，作为当前菜单href的数字
            Menu searchMenu = new Menu();
            searchMenu.setParentId("0");
            List<Menu> menuList = dao.selectList(new QueryWrapper<>(searchMenu));
            int max = 0;
            for(Menu m : menuList){
                String href = m.getHref();
                if(StringUtils.isNotBlank(href)){
                    String hrefIntString = href.split("#")[1];
                    if(StringUtils.isNumeric(hrefIntString)){
                        Integer mInt = Integer.valueOf(hrefIntString);
                        if(max < mInt){
                            max = mInt;
                        }
                    }
                }
            }
            menu.setHref("#" + (max + 1));
        }
        if(StringUtils.isBlank(menu.getIsShow())){
            menu.setIsShow(Global.YES);
        }
        return super.saveOrUpdate(menu);
    }

    @Override
    public List<Menu> findByParentId(String parentId) {
        return dao.findByParentId(parentId);
    }
}
